package com.mrjy.live.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mrjy.common.entity.OrderInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.WisPayment;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.live.bo.IWisPaymentBo;

import com.tencent.common.Util;
import com.tencent.protocol.pay_protocol.ScanPayResData;

@Controller
@RequestMapping("live/wisPayment")
public class WisPamentController{
	
	@Resource
	private IWisPaymentBo  wisPaymentBo;
	
	/**
	 * 创建订单
	 * @return
	 */
	@RequestMapping("/createPayment")
	@ResponseBody
	public Object createPayment(WisPayment wisPayment, HttpSession session){
		UserInfo userInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
		wisPayment.setUserId(userInfo.getId());
		return wisPaymentBo.addPayment(wisPayment);
	}
	
	/**
	 * 删除订单
	 * @return
	 */
	@RequestMapping("/deletePayment")
	@ResponseBody
	public Object deletePayment(WisPayment wisPayment){
		return wisPaymentBo.deletePayment(wisPayment);
	}
	
	/**
	 * 查找订单
	 * @return
	 */
	@RequestMapping("/queryPayment")
	@ResponseBody
	public Object queryPayment(WisPayment wisPayment, HttpSession session){
		UserInfo userInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
//		wisPayment.setUserId(userInfo.getId());
		return wisPaymentBo.queryPayment(wisPayment, userInfo);
	}
	
	/**
	 * 开始订单
	 * @return
	 */
	@RequestMapping("/beginPayment")
	@ResponseBody
	public Object beginPayment(WisPayment wisPayment, HttpSession session){
		UserInfo userInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
		return wisPaymentBo.beginPayment(wisPayment, userInfo);
	}
	
	/**
	 * 提交订单
	 * @return
	 */
	@RequestMapping("/submitPayment")
	@ResponseBody
	public Object submitPayment(WisPayment wisPayment, HttpSession session){
		UserInfo userInfo = ((UserInfo) session.getAttribute(GlobalConstant.USER_INFO));
		return wisPaymentBo.submitPayment(wisPayment, userInfo);
	}
	
	/**
	 * 根据订单号获取订单信息
	 * 
	 * @return
	 */
	@RequestMapping("/getPaymentByCode")
	@ResponseBody
	public Object getPaymentByCode(WisPayment wisPayment) {
		return wisPaymentBo.getPaymentByCode(wisPayment.getCode());
	}
	
	/**
	 * 检查是否已经支付成功
	 * 
	 * @return
	 */
	@RequestMapping("/validatePay")
	@ResponseBody
	public Object validatePay(WisPayment wisPayment) {
		return wisPaymentBo.validatePay(wisPayment.getCode());
	}
	
	/**
	 * 支付宝页面跳转同步通知
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/returnUrl")
	public Object returnUrl(HttpServletRequest request) throws UnsupportedEncodingException {
		// 获取支付宝GET过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}
		// 商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		// 付款金额
		String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");
		Float money = Float.parseFloat(total_fee);
		WisPayment wisPayment = wisPaymentBo.returnUrl(params, out_trade_no, trade_no, trade_status, money);
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setUrl(wisPayment.getUrl());
		orderInfo.setMessageString(wisPayment.getMessageString());
		request.setAttribute("orderInfo", orderInfo);
		return wisPayment.getMessageString();
	}
	
	/**
	 * 支付宝服务器异步通知
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/notifyUrl")
	@ResponseBody
	public void notifyUrl(HttpServletRequest request,HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		// 商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]: valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"),
			// "gbk");
			params.put(name, valueStr);
		}
		// 支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
		// 交易状态
		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		// 付款金额
		String total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"), "UTF-8");
		Float money = Float.parseFloat(total_fee);
		String result = wisPaymentBo.notifyUrl(params, out_trade_no, trade_no, trade_status, money);
		out.println(result);
		out.flush();
		out.close();
	}
	
	
	/**
	 * 微信服务器异步通知
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/WXnotifyUrl")
	@ResponseBody
	public void WXnotifyUrl(HttpServletRequest request,HttpServletResponse response) throws IOException {
		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
		System.out.println("微信支付回调数据开始");
		String inputLine;
		String notityXml = "";
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("接收到的报文：" + notityXml);
		// 将返回的XML数据映射到Java对象
		ScanPayResData scanPayResData = (ScanPayResData) Util.getObjectFromXML(notityXml, ScanPayResData.class);
		String resXml = wisPaymentBo.WXnotifyUrl(scanPayResData);
		out.write(resXml.getBytes());
		out.flush();
		out.close();
		System.out.println("微信支付回调数据结束");
	}
	
	/**
	 *
	 * 
	 */
	@RequestMapping("/livePaymentList")
	@ResponseBody
	public Object livePaymentList(WisPayment wisPayment,HttpSession session){
		UserInfo userInfo = (UserInfo)session.getAttribute(GlobalConstant.USER_INFO);
		if(userInfo.getRoleId()!=1){
			wisPayment.setSchoolId(userInfo.getSchoolId());
		}
		return wisPaymentBo.livePaymentList(wisPayment);
	}
	
	/**
	 *交易金额
	 * 
	 */
	@RequestMapping("/countBySchoolMoney")
	@ResponseBody
	public Object countBySchoolMoney(WisPayment wisPayment){
		return wisPaymentBo.countBySchoolMoney(wisPayment);
	}
}
